package qj.ps.sla.vfg;

import java.util.LinkedList;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import qj.util.*;
import qj.util.XmlUtil.Tag;
import qj.util.funct.Fs;
import qj.util.funct.P1;

@SuppressWarnings({"rawtypes","unchecked"})
public class MobileCodeMain {
	public static void main(String[] args) {
		final String content = IOUtil.toString(MobileCodeMain.class.getResourceAsStream("mobilenetworkcode_wiki.txt"));
		
		LinkedList<Map> list = step1(content);
		
		System.out.println("##### Source: http://en.wikipedia.org/wiki/Mobile_Network_Code  #####");
		System.out.println();
		for (final Map map : list) {
			final String countryCode = (String) map.get("code");
			final boolean[] known = {false};
			XmlUtil.eachTag("tr", (String) map.get("content"), Fs.skip(1, new P1<Tag>() {public void e(Tag obj) {
				if (known[0]) {
					return;
				}
				LinkedList<Tag> tds = new LinkedList<Tag>();
				XmlUtil.eachTag("td",obj.innerHtml, Fs.store(tds));
				
				if (tds.size() == 0) {
					return;
//					System.out.println((String) map.get("code"));
//					System.out.println(obj.innerHtml);
				}
				
				if (tds.get(2).innerHtml.contains("Vodafone")) {
//					if (known[0]) {
//						System.out.println("# Duplicated");
//					}
					System.out.println("# Country: " + map.get("name") + ", brand: " + XmlUtil.normalize(tds.get(2).innerHtml) + ", operator: " + XmlUtil.normalize(tds.get(3).innerHtml));
					System.out.println(countryCode + "=" + tds.get(0).innerHtml + tds.get(1).innerHtml);
					System.out.println();
					known[0] = true;
//					System.exit(0);
				}
				
			}}));
//			XmlUtil.nextTag("tr", content, 0).range;
			
		}
//		System.out.println("total: " + list.size());
	}
	// International 901	28	Vodafone

	public static LinkedList<Map> step1(final String content) {
		final LinkedList<Map> list = new LinkedList<Map>();
		final Map[] pending = {null};
		RegexUtil.each(Pattern.compile("(?:([^>]+)</a>[^>-]*? - )?([A-Z0-9]+)</span></h4>"), content, new P1<Matcher>() {public void e(Matcher m) {
			if (pending[0]!=null) {
				Map p = pending[0];
				p.put(
						"content", content.substring((Integer)p.get("from"), m.start())
						);
				p.put("to", m.start());
				list.add(p);
			}
			pending[0] = Cols.map(
					"name", m.group(1),
					"code", m.group(2),
					"from", m.end()
					);
//			list.add(map);
		}});
		
		Map p = pending[0];
		p.put("content", 
				content.substring((Integer)p.get("from"), content.indexOf("\"mw-headline\" id=\"References\">References</span></h2>"))
				);
		list.add(p);
		
		return list;
	}
}
